<?php
// 显示所有错误
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 测试记录
$tests = [];

// 测试PHP版本
$phpVersion = phpversion();
$tests[] = [
    'name' => 'PHP版本检查',
    'result' => version_compare($phpVersion, '7.0.0', '>='),
    'message' => "PHP版本: $phpVersion" . (version_compare($phpVersion, '7.0.0', '>=') ? ' (兼容)' : ' (不兼容，需要PHP 7.0.0或更高版本)')
];

// 测试会话
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
$sessionWorking = isset($_SESSION) ? true : false;
$tests[] = [
    'name' => '会话(Session)功能检查',
    'result' => $sessionWorking,
    'message' => $sessionWorking ? '会话功能正常' : '会话功能异常，可能影响登录状态保存'
];

// 检查PDO扩展
$pdoAvailable = extension_loaded('pdo') && extension_loaded('pdo_mysql');
$tests[] = [
    'name' => 'PDO数据库扩展检查',
    'result' => $pdoAvailable,
    'message' => $pdoAvailable ? 'PDO扩展可用' : 'PDO扩展或PDO MySQL驱动不可用，这会导致无法连接数据库'
];

// 检查数据库配置
$dbConfigOk = false;
$dbConfigMessage = "";
try {
    require_once __DIR__ . '/../config/database.php';
    $dbConfigOk = defined('DB_HOST') && defined('DB_USERNAME') && defined('DB_PASSWORD') && defined('DB_NAME');
    $dbConfigMessage = $dbConfigOk ? '数据库配置文件加载成功' : '数据库配置不完整';
} catch (Exception $e) {
    $dbConfigMessage = '加载数据库配置出错: ' . $e->getMessage();
}
$tests[] = [
    'name' => '数据库配置检查',
    'result' => $dbConfigOk,
    'message' => $dbConfigMessage
];

// 测试数据库连接
$dbConnectionOk = false;
$dbConnectionMessage = "";
if ($dbConfigOk) {
    try {
        $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET;
        $pdo = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $dbConnectionOk = true;
        $dbConnectionMessage = '成功连接到数据库';
    } catch (PDOException $e) {
        $dbConnectionMessage = '数据库连接失败: ' . $e->getMessage();
    }
} else {
    $dbConnectionMessage = '由于数据库配置问题，跳过连接测试';
}
$tests[] = [
    'name' => '数据库连接测试',
    'result' => $dbConnectionOk,
    'message' => $dbConnectionMessage
];

// 检查管理员账户是否存在
$adminExists = false;
$adminMessage = "";
if ($dbConnectionOk) {
    try {
        $stmt = $pdo->query("SELECT COUNT(*) FROM " . DB_PREFIX . "users WHERE role = 'admin'");
        $adminCount = $stmt->fetchColumn();
        if ($adminCount > 0) {
            $adminExists = true;
            $adminMessage = "系统中存在 $adminCount 个管理员账户";
        } else {
            $adminMessage = "系统中不存在管理员账户，请先创建管理员";
        }
    } catch (PDOException $e) {
        $adminMessage = '检查管理员账户失败: ' . $e->getMessage() . ' (可能是表不存在)';
    }
}
$tests[] = [
    'name' => '管理员账户检查',
    'result' => $adminExists,
    'message' => $adminMessage
];

// 检查必要的文件
$requiredFiles = [
    'includes/functions.php',
    'includes/AdminAuth.php',
    'login.php',
    'index.php',
    '../include/Database.php'
];
$missingFiles = [];

foreach ($requiredFiles as $file) {
    if (!file_exists(__DIR__ . '/' . $file)) {
        $missingFiles[] = $file;
    }
}

$filesOk = empty($missingFiles);
$filesMessage = $filesOk ? '所有必要文件都存在' : '缺少以下文件: ' . implode(', ', $missingFiles);

$tests[] = [
    'name' => '文件完整性检查',
    'result' => $filesOk,
    'message' => $filesMessage
];

// 计算整体状态
$allTestsPassed = true;
foreach ($tests as $test) {
    if (!$test['result']) {
        $allTestsPassed = false;
        break;
    }
}

// 测试创建管理员
$createAdminStatus = "";
if (!$adminExists && $dbConnectionOk && $filesOk) {
    try {
        $username = 'admin';
        $password = password_hash('admin123', PASSWORD_DEFAULT);
        $email = 'admin@example.com';
        
        // 检查表是否存在
        $tableExists = false;
        $stmt = $pdo->query("SHOW TABLES LIKE '" . DB_PREFIX . "users'");
        if ($stmt->rowCount() > 0) {
            $tableExists = true;
        }
        
        if ($tableExists) {
            // 插入管理员账户
            $stmt = $pdo->prepare("INSERT INTO " . DB_PREFIX . "users 
                (username, password, email, role, status, created_at) VALUES 
                (?, ?, ?, 'admin', 'active', NOW())");
                
            $stmt->execute([$username, $password, $email]);
            
            if ($stmt->rowCount() > 0) {
                $createAdminStatus = "<div class='alert alert-success'>已自动创建管理员账户！用户名: admin, 密码: admin123</div>";
            } else {
                $createAdminStatus = "<div class='alert alert-warning'>创建管理员账户失败</div>";
            }
        } else {
            $createAdminStatus = "<div class='alert alert-warning'>users表不存在，请先运行setup_tables.php</div>";
        }
    } catch (PDOException $e) {
        $createAdminStatus = "<div class='alert alert-danger'>创建管理员错误: " . $e->getMessage() . "</div>";
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KidsMind - 登录诊断</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card shadow">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0">KidsMind 登录诊断工具</h4>
                    </div>
                    <div class="card-body">
                        <h5 class="card-title mb-4">登录系统诊断结果</h5>
                        
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>测试项目</th>
                                    <th>状态</th>
                                    <th>详细信息</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($tests as $test): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($test['name']); ?></td>
                                    <td>
                                        <?php if ($test['result']): ?>
                                            <span class="badge bg-success">成功</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger">失败</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($test['message']); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        
                        <?php echo $createAdminStatus; ?>
                        
                        <div class="mt-4">
                            <?php if ($allTestsPassed): ?>
                                <div class="alert alert-success">
                                    <strong>所有测试通过！</strong> 您现在应该能够登录系统了。
                                </div>
                                <p>请使用以下信息登录：</p>
                                <ul>
                                    <li>用户名: admin</li>
                                    <li>密码: admin123</li>
                                </ul>
                            <?php else: ?>
                                <div class="alert alert-warning">
                                    <strong>有一个或多个测试未通过。</strong> 请先修复这些问题。
                                </div>
                                <p>建议操作步骤：</p>
                                <ol>
                                    <li>运行 <a href="setup_tables.php">setup_tables.php</a> 创建必要的数据表</li>
                                    <li>运行 <a href="create_admin.php">create_admin.php</a> 创建管理员账户</li>
                                    <li>运行 <a href="advanced_fix.php">高级修复工具</a> 修复系统问题</li>
                                    <li>确保数据库配置正确（检查config/database.php）</li>
                                </ol>
                            <?php endif; ?>
                        </div>
                        
                        <div class="mt-4">
                            <a href="login.php" class="btn btn-primary">尝试登录</a>
                            <a href="setup_tables.php" class="btn btn-warning">创建数据表</a>
                            <a href="add_test_data.php" class="btn btn-success">添加测试数据</a>
                            <a href="advanced_fix.php" class="btn btn-secondary">高级修复</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html> 